package c3p0;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.junit.Test;

import java.beans.PropertyVetoException;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

/**
 * c3p0 连接池
 * Created by kevin on 2020/3/26.
 */
public class Demo1 {
    private static Properties properties = null;
    static {
        try {
            InputStream in = Demo1.class.getClassLoader().getResourceAsStream("dbconfig.properties");
            properties = new Properties();
            properties.load(in);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 代码配置
     */
    @Test
    public void fun1(){
        try {
            /**
             * 1、创建连接池对象
             * 2、配置4大参数(驱动类,url,name,password)
             * 3、配置池参数
             * 4、得到连接对象
             */
            //1、创建连接池对象
            ComboPooledDataSource comboPooledDataSource  = new ComboPooledDataSource();
            //2、配置4大参数(驱动类,url,name,password)
            comboPooledDataSource.setDriverClass(properties.getProperty("driverClassName"));
            comboPooledDataSource.setJdbcUrl(properties.getProperty("url"));
            comboPooledDataSource.setUser(properties.getProperty("name"));
            comboPooledDataSource.setPassword(properties.getProperty("password"));
            //3、配置连接池参数
            comboPooledDataSource.setAcquireIncrement(5);
            comboPooledDataSource.setInitialPoolSize(20);
            comboPooledDataSource.setMinPoolSize(2);
            comboPooledDataSource.setMaxPoolSize(50);
            //4、得到连接池对象
            Connection connection = comboPooledDataSource.getConnection();
            System.out.println(connection.getClass().getName());
            connection.close();
        } catch (PropertyVetoException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }

    }

    /**
     * 配置文件的默认配置
     */
    @Test
    public void fun2(){
        try {
            /**
             * 在创建连接池对象时,这个对象就会自动加载配置文件!
             */
            //默认配置 default-config
            ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource();
            //命名配置 named-config
            //ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource("myConfig");
            Connection connection = comboPooledDataSource.getConnection();
            System.out.println(connection.getClass().getName());
            connection.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
